from PyQt5.QtCore import QThread, QTimer, pyqtSignal


class WarningClass(QThread):
    __warning_str = ''  # 告警信息
    __warning_period = 3  # 告警重复显示周期（单位：秒）
    __warning_counter = 0  # 距离上次告警开始计数,无告警状态时设置为0
    __warning_level = 0  # 告警等级 0-通知信息白色 1-异常提示，黄色 2-紧急提示，红色

    callback_publish = None  # 告警信息发布回调函数
    callback_monitor = None  # 告警信息检测回调函数
    sig_warning_publish = pyqtSignal(str)

    def __init__(self, warning_str="", warning_period=3, warning_level=0, callback_monitor=None,
                 callback_publish=None):  # 定义对象时初始化mqtt客户端
        super().__init__()
        self.__warning_str = warning_str
        self.__warning_period = warning_period
        self.__warning_level = warning_level

        self.callback_monitor = callback_monitor
        self.callback_publish = callback_publish

        self.send_timer = QTimer()
        self.send_timer.timeout.connect(self._1HzProcess)
        self.send_timer.setInterval(1000)
        self.send_timer.start()

    def _1HzProcess(self):
        if self.callback_monitor is not None and self.callback_publish is not None:
            if self.callback_monitor():
                if self.__warning_counter == 0:  # 在一个告警周期内只调用一次告警信息发布函数
                    self.callback_publish(self.__warning_level, self.__warning_str)
                self.__warning_counter += 1
                self.__warning_counter = self.__warning_counter % self.__warning_period
            else:
                self.__warning_counter = 0
